package com.chb.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chb.system.mapper.LoginInfoMapper;
import com.chb.system.service.LoginInfoService;
import com.chb.system.vo.LoginInfoVo;
import com.hos.entity.sys.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author ：张家琪
 * @date ：Created in 2023/12/18 10:30
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class LoginInfoServiceImpl implements LoginInfoService {
    @Resource
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<LoginInfo> getAllLoginInfo() {
        LambdaQueryWrapper<LoginInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(LoginInfo::getLoginTime);
        return loginInfoMapper.selectList(wrapper);
    }

    @Override
    public Page<LoginInfo> selectAllLoginInfoByCond(LoginInfoVo loginInfoVo) {
        Page<LoginInfo> page = new Page<>(loginInfoVo.getPageNum(), loginInfoVo.getPageSize());
        LambdaQueryWrapper<LoginInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(loginInfoVo.getUserName())) {
            wrapper.like(LoginInfo::getUserName, loginInfoVo.getUserName());
        }
        if (StringUtils.hasText(loginInfoVo.getLoginAccount())) {
            wrapper.like(LoginInfo::getLoginAccount, loginInfoVo.getLoginAccount());
        }
        if (StringUtils.hasText(loginInfoVo.getIpAddr())) {
            wrapper.like(LoginInfo::getIpAddr, loginInfoVo.getIpAddr());
        }
        if (StringUtils.hasText(loginInfoVo.getLoginStatus())) {
            wrapper.eq(LoginInfo::getLoginStatus, loginInfoVo.getLoginStatus());
        }
        if (StringUtils.hasText(loginInfoVo.getLoginType())) {
            wrapper.eq(LoginInfo::getLoginType, loginInfoVo.getLoginType());
        }
        if (Objects.nonNull(loginInfoVo.getDateRange())) {
            wrapper.between(LoginInfo::getLoginTime, loginInfoVo.getDateRange()[0], loginInfoVo.getDateRange()[1]);
        }
        wrapper.orderByDesc(LoginInfo::getLoginTime);
        return loginInfoMapper.selectPage(page, wrapper);
    }

    @Override
    public Integer deleteLoginInfoByIds(List<Long> ids) {
        return loginInfoMapper.deleteBatchIds(ids);
    }

    @Override
    public Integer clearLoginInfo() {
        return loginInfoMapper.delete(null);
    }

    /**
     * 增加登录日志
     *
     * @param loginInfo
     */
    @Override
    public Integer addLoginInfo(LoginInfo loginInfo) {
        return loginInfoMapper.insert(loginInfo);
    }
}